import { NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import bcrypt from 'bcryptjs'

const prisma = new PrismaClient()

export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
) {
  try {
    const { oldPassword, newPassword, isReset } = await request.json()
    
    const user = await prisma.user.findUnique({
      where: { id: params.id }
    })

    if (!user) {
      return NextResponse.json({ error: '用户不存在' }, { status: 404 })
    }

    if (!isReset) {
      const isValid = await bcrypt.compare(oldPassword, user.password)
      if (!isValid) {
        return NextResponse.json({ error: '当前密码错误' }, { status: 401 })
      }
    }

    const hashedPassword = await bcrypt.hash(newPassword, 10)
    await prisma.user.update({
      where: { id: params.id },
      data: { password: hashedPassword }
    })

    return NextResponse.json({ message: '密码修改成功' })
  } catch (error) {
    return NextResponse.json({ error: '密码修改失败' }, { status: 500 })
  }
} 